// 合作房源相关公共方法
import api from "../common/api";
import p from "../utils/platform";
/** 
 * key: id
 * value: {
 *  data 房源数据
 *  pendingList: Array<Promise> 等待列表
 * }
 */
const cacheMap = {}
export const cooperationBehavior = Behavior({
  methods: {
    /**
     * 通过合作房源id获取房源信息（具有缓存作用，并且同时请求也只请求接口一次）
     * @param {*} id 合作房源id
     * @param {*} force 是否强制重新请求
     */
    getInfoByCooperationId(id, force=false) {
      if (!id) return Promise.reject()
      if (force) { delete cacheMap[id] }
      
      let cache = cacheMap[id]
      if (cache && cache.data) return Promise.resolve(cache.data)

      cache = cacheMap[id] = cacheMap[id] || {}

      if (cache.pendingList) {
        return new Promise((resolve, reject) => {
          cache.pendingList.push((v) => { resolve(v) })
        });

      } else {
        cache.pendingList = []
        
        return new Promise((resolve, reject) => {
          api.getCooperationInfo({cooperationId: id}, ({data}) => {
            if (data && data.content) {
              const { content } = data
              cache.data = content
              resolve(content)
              
              if (cache.pendingList.length) {
                cache.pendingList.forEach((fn) => fn(content));
              }
              cache.pendingList = null

            } else {
              delete cacheMap[id]
            }
          }, () => {
            delete cacheMap[id]
          })
        })
      }
    },

    /** 
     * 虚拟号拨号
     * cooperationId 就某个合作房开始虚拟号联系
     * mobile 拨出号重定义
     * inviteInfo 无则表示客源方   有则表示房源方
     */
    callVirtualPhonNumber(cooperationId, mobile, inviteInfo) {
      this.getInfoByCooperationId(cooperationId).then((content) => {
        // if (content.hmCooperationDelVO.cooperationDown) {
        //   return wx.showToast({ icon: 'none', title: '该房源已下架~', })
        // }

        const jjrVO = content.jjrVO
        const params = {
          delId: content.hmCooperationDelVO.delId,
          cooperationId,
          houseOwnerId: jjrVO.id,
          houseOwnerUnionid: jjrVO.wechatUnionid,
        }
        if (mobile) {
          params.editedMobile = mobile
        }

        let fetchApi = api.getVirtualNumber;
        if (inviteInfo && inviteInfo.houseInviteId) {
          Object.assign(params, inviteInfo)
          fetchApi = api.getVirtualPhoneNumber
        }

        fetchApi(params, ({data}) => {
          const content = data.content
          if (data.isSuccess && content && content.phoneNumber) {
            wx.makePhoneCall({
              phoneNumber: String(content.phoneNumber)
            })
          } else {
            this.failPhoneHandler(cooperationId, jjrVO.wechatUnionid)
          }

          if (mobile) {
            getApp().refreshSession()
          }
        }, () => {
          this.failPhoneHandler(cooperationId, jjrVO.wechatUnionid)
        })
      });
    },

    
    /**
     * 新的打电话接口
     *  "toUserId":"", -- 拨打的对方
     * "cooperationId":"aa" -- 合作房源信息，非必填
     */
    callVmPhoneNumberNew(toUserId,cooperationId){
      return new Promise((resolve, reject) => {
        api.getVirtualNumberNoNeedCooperationInfo({toUserId,cooperationId}, ({data}) => {
          const { content } = data;
          if (content && content.virtualNum) {
            wx.makePhoneCall({
              phoneNumber: String(content.virtualNum),
            });
            resolve()
          } else {
            this.failPhoneHandler()
            reject()
          }
        })
      })
    },

    // 绑定虚拟号失败
    failPhoneHandler(cooperationId, unionid) {
      p.showModal({
        content: "当前电话无法呼叫，可以通过聊天进行联系～",
        cancelText: "取消",
        confirmText: "立即沟通"
      })
      .then((res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/im/imMessagelist/imMessagelist?unionid=${unionid}&cooperationId=${cooperationId}`,
          })
        } 
      })
    },
  }
})